<template>
  <div id="imooc-container" :ref="refName">
    <slot></slot>
  </div>
</template>

<script>
import { ref, getCurrentInstance, onMounted, onUnmounted, nextTick } from 'vue'
import { debounce } from '../../utils'
export default {
  name: "ImoocContainer",
  props: {
    options: {
      type: Object,
      default: () => {
        return {
          width: 0,
          height: 0
        }
      }
    }
  },
  setup(ctx) {
    // eslint-disable-next-line vue/no-setup-props-destructure
    const { options } = ctx
    const refName = 'imoocContainer'
    const width = ref(0);
    const height = ref(0);
    const originalWidth = ref(0);
    const originalHeight = ref(0);
    const context = getCurrentInstance().ctx;
    let dom;

    const initSize = () => {
      return new Promise((resolve) => {
        nextTick(() => {
          dom = context.$refs[refName];
          /** 获取大屏的真实尺寸 **/
          if (options.width && options.height) {
            width.value = options.width;
            height.value = options.height;
          } else {
            width.value = dom.clientWidth;
            height.value = dom.clientHeight;
          }
          /** 获取画布的尺寸 **/
          if (!originalWidth.value || !originalHeight.value) {
            originalWidth.value = window.screen.width;
            originalHeight.value = window.screen.height;
          }
          console.log(width.value, height.value, originalWidth.value, originalHeight.value);
          resolve();
        })
      })
    }

    const updateSize = () => {
      if (width.value && height.value) {
        dom.style.width = `${width.value}px`;
        dom.style.height = `${height.value}px`;
      } else {
        dom.style.width = `${originalWidth.value}px`;
        dom.style.height = `${originalHeight.value}px`;
      }
    }

    const updateScale = () => {
      /** 获取真实的视口尺寸 **/
      const currentWidth = document.body.clientWidth;
      const currentHeight = document.body.clientHeight;
      /** 获取大屏最终的宽高 **/
      const realWidth = width.value || originalWidth.value;
      const realHeight = height.value || originalHeight.value;

      const widthScale = currentWidth / realWidth;
      const heightScale = currentHeight / realHeight;
      dom.style.transform = `scale(${widthScale}, ${heightScale})`
    }

    const onResize = async () => {
      console.log('onResize');
      await initSize();
      updateScale();
    }

    onMounted(async () => {
      await initSize();
      updateSize();
      updateScale();
      window.addEventListener('resize', debounce(1000, onResize));
    })

    onUnmounted(() => {
      window.removeEventListener('resize', onResize);
    })

    return {
      refName
    }
  }
}
</script>

<style lang="scss" scoped>
#imooc-container {
  position: fixed;
  top: 0;
  left: 0;
  overflow: hidden;
  z-index: 999;
  transform-origin: left top;
}
</style>